package edu.nus.mtech.sem1.ca.utils;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;

import edu.nus.mtech.sem1.ca.data.ConfigurationUtils;

/**
 * Ah. We all know System.out is a sick way to log. An even sicker way is here. 
 * This class is meant to provide exception-free way to log into a file configured in the Telephony.properties
 * Seriously, who would want to fail the application if the logger fails. So, if there is an exception while calling 
 * these methods, the angry goblin eats them all
 *
 */
public class Logger {

	public static PrintWriter printWriter;
	
	private static void initialize() {
		try {
			Properties applicationConfiguration = ConfigurationUtils.loadConfiguration(); 
			FileWriter fileWriter=new FileWriter(System.getProperty("user.dir")+ "/"+applicationConfiguration.getProperty(TelephonyConstants.LOG_FILE_LOCATION));
			BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
			printWriter=new PrintWriter(bufferedWriter);
		} catch (IOException e) {
			System.err.print("Logger could not initialized");
			e.printStackTrace();
		}

	}
	
	/**
	 * @param logMessage
	 */
	public static void log(String logMessage){
		try {
			if (printWriter==null){
				initialize();
			}
			printWriter.println(logMessage);
			//Flush immediately coz of log refresh issues
			printWriter.flush();
		} catch (Exception e) {
			//e.printStackTrace(); //burp
			System.err.println("Error while logging. God knows why.. or this exception could give you a clue"+e.getMessage());
		}
	}
	
	public static void log(Object logMessage){
		try {
			if (printWriter==null){
				initialize();
			}
			printWriter.println(logMessage);
			printWriter.flush();
		} catch (Exception e) {
			//e.printStackTrace(); //burp
			System.err.println("Error while logging. God knows why.. or this exception could give you a clue"+e.getMessage());
		}
	}
}
